<template>
  <div class="permission">
    <el-card>
      <div style="text-align: right">
        <el-button
          type="primary"
          size="mini"
          @click="addClick('0', 1)"
        >添加菜单</el-button>
      </div>
      <el-table :data="list" row-key="id">
        <el-table-column label="菜单名称" prop="name" />
        <el-table-column label="权限标识" prop="code" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <div>
              <el-button
                type="text"
                @click="addClick(row.id, 1)"
              >添加菜单</el-button>
              <el-button
                type="text"
                @click="addClick(row.id, 2)"
              >添加按钮</el-button>
              <el-button type="text" @click="editClick(row)">编辑</el-button>
              <el-button type="text" @click="del(row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 编辑弹框组件 -->
    <Add
      ref="add"
      :show-add="showAdd"
      @update:showAdd="showAdd = $event"
      @getData="getData"
    />
  </div>
</template>

<script>
import { sysPermission, sysPermissionDelete } from '@/api/permission.js'
import Add from './components/add'
export default {
  components: {
    Add
  },
  data() {
    return {
      list: [],
      showAdd: false
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 获取权限列表数据
    async getData() {
      const res = await sysPermission()
      this.list = this.changeData(res.data, '0')
      console.log(res)
    },
    // 树形数据转换
    changeData(arr, pid) {
      return arr.filter((item) => {
        if (item.pid === pid) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    },
    // 新增点击
    addClick(pid, type) {
      this.showAdd = true
      this.$refs.add.form.pid = pid
      this.$refs.add.form.type = type
      this.$refs.add.mode = 'add'
    },
    // 编辑点击
    editClick(row) {
      this.showAdd = true
      this.$refs.add.mode = 'edit'
      // 数据的深拷贝
      this.$refs.add.form = JSON.parse(JSON.stringify(row))
    },
    // 删除点击
    del(id) {
      this.$confirm('您确定要删除当前行权限数据嘛?', '温馨提示')
        .then(async() => {
          await sysPermissionDelete(id)
          this.$message.success('删除成功')
          this.getData()
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.permission {
}
</style>
